package com.campus.merchant.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.bean.common.Resp;
import com.campus.common.exception.BusinessException;
import com.campus.merchant.bean.apply.MerchantApplyBean;
import com.campus.merchant.bean.merchant.MerchantStatusUpdateBean;
import com.campus.merchant.bean.merchant.MerchantUpdateBean;
import com.campus.merchant.entity.Merchant;
import com.campus.merchant.entity.MerchantApply;
import com.campus.merchant.entity.MerchantBusinessHours;
import com.campus.merchant.entity.MerchantCategory;
import com.campus.merchant.mapper.MerchantApplyMapper;
import com.campus.merchant.mapper.MerchantBusinessHoursMapper;
import com.campus.merchant.mapper.MerchantMapper;
import com.campus.merchant.vo.merchant.MerchantApplyVO;
import com.campus.merchant.vo.merchant.MerchantVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商户表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-17
 */
@Service
public class MerchantService extends ServiceImpl<MerchantMapper, Merchant> {
    @Autowired
    private MerchantApplyMapper merchantApplyMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerchantBusinessHoursMapper merchantBusinessHoursMapper;
    @Autowired
    private MerchantCategoryService merchantCategoryService;

    /**
     * 查询商户入驻状态
     * 
     * @param merchantUserId 商家用户ID
     * @return 状态、拒绝原因
     */
    public Map<String, Object> getEntryStatus(Integer merchantUserId) {
        Map<String, Object> result = new HashMap<>();
        // 先查merchant表，已入驻且审核通过
        Merchant merchant = merchantMapper.selectOne(Wrappers.lambdaQuery(Merchant.class)
                .eq(Merchant::getMerchantUserId, merchantUserId));
        if (merchant != null) {
            if(merchant.getInfoCompleted() == 1){
                result.put("status", "审核通过且已完善");
            }else{
                result.put("status", "审核通过但未完善");
            }
            return result;
        }
        // 查申请表
        MerchantApply apply = merchantApplyMapper.selectOne(Wrappers.lambdaQuery(MerchantApply.class)
                .eq(MerchantApply::getMerchantUserId, merchantUserId)
                .orderByDesc(MerchantApply::getCreateTime)
                .last("limit 1"));
        if (apply == null) {
            result.put("status", "未入驻");
        } else if (apply.getStatus() == 0) {
            result.put("status", "审核中");
        } else if (apply.getStatus() == 2) {
            result.put("status", "审核拒绝");
            result.put("rejectReason", apply.getRejectReason());
        }
        return result;
    }

    /**
     * 提交商户入驻申请
     * 
     * @param bean 表单Bean
     * @return 提交结果
     */
    public Resp submitMerchantApply(MerchantApplyBean bean) {
        try {
            MerchantApply apply = new MerchantApply();
            apply.setMerchantUserId(bean.getMerchantUserId());
            apply.setSubMchid(bean.getSubMchid());
            apply.setName(bean.getName());
            apply.setLogo(bean.getLogo());
            apply.setAddress(bean.getAddress());
            apply.setPhone(bean.getPhone());
            apply.setLicenseImage(bean.getLicenseImage());
            apply.setShopImage(bean.getShopImage());
            apply.setDescription(bean.getDescription());
            apply.setCanteenId(bean.getCanteenId());
            apply.setStatus(0); // 0-待审核
            apply.setCreateTime(LocalDateTime.now());
            merchantApplyMapper.insert(apply);
            return Resp.success("提交成功，等待审核");
        } catch (Exception e) {
            return Resp.error("提交失败: " + e.getMessage());
        }
    }

    /**
     * 查询商户最新入驻申请记录
     *
     * @param merchantUserId 商家用户ID
     * @return 最新入驻申请VO
     */
    public MerchantApplyVO getLatestEntryApply(Integer merchantUserId) {
        MerchantApply apply = merchantApplyMapper.selectOne(Wrappers.lambdaQuery(MerchantApply.class)
                .eq(MerchantApply::getMerchantUserId, merchantUserId)
                .orderByDesc(MerchantApply::getCreateTime)
                .last("limit 1"));
        if (apply == null) {
            return null;
        }
        MerchantApplyVO vo = new MerchantApplyVO();
        BeanUtil.copyProperties(apply, vo);
        return vo;
    }

    /**
     * 根据商家ID查询商家信息
     * @param merchantId 商家ID
     * @return 商家信息VO
     */
    public MerchantVO getMerchantById(Integer merchantId) {
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            return null;
        }
        MerchantVO vo = new MerchantVO();
        BeanUtil.copyProperties(merchant, vo);

        List<MerchantBusinessHours> merchantBusinessHoursList = merchantBusinessHoursMapper.selectList(Wrappers.<MerchantBusinessHours>lambdaQuery().eq(MerchantBusinessHours::getMerchantId, merchantId));
        vo.setBusinessHoursList(merchantBusinessHoursList);

        // 获取商户分类
        List<MerchantCategory> merchantCategories = merchantCategoryService.list(Wrappers.<MerchantCategory>lambdaQuery().eq(MerchantCategory::getMerchantId, merchantId));
        List<Integer> categoryIds = merchantCategories.stream().map(MerchantCategory::getCategoryId).collect(java.util.stream.Collectors.toList());
        vo.setCategoryIds(categoryIds);

        return vo;
    }

    /**
     * 更新商家信息
     * @param merchantUpdateBean 商家更新信息
     * @return 更新结果
     */
    public void updateMerchantInfo(MerchantUpdateBean merchantUpdateBean) {
        Merchant merchant = new Merchant();
        BeanUtil.copyProperties(merchantUpdateBean, merchant);
        merchant.setInfoCompleted(1);
        merchantMapper.updateById(merchant);

        // 更新商户分类关联
        if (merchantUpdateBean.getCategoryIds() != null) {
            // 先删除原有的分类关联
            merchantCategoryService.remove(Wrappers.<MerchantCategory>lambdaQuery().eq(MerchantCategory::getMerchantId, merchantUpdateBean.getId()));
            
            // 添加新的分类关联
            for (Integer categoryId : merchantUpdateBean.getCategoryIds()) {
                MerchantCategory merchantCategory = new MerchantCategory();
                merchantCategory.setMerchantId(merchantUpdateBean.getId());
                merchantCategory.setCategoryId(categoryId);
                merchantCategory.setCreateTime(LocalDateTime.now());
                merchantCategoryService.save(merchantCategory);
            }
        }
    }

    /**
     * 更新商户营业状态
     * @param bean 商户营业状态更新参数
     * @return 更新后的商户VO
     */
    public void updateMerchantStatus(MerchantStatusUpdateBean bean) {
        Merchant merchant = merchantMapper.selectById(bean.getId());
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        //如果要更新为营业中，则需要判断是否设置了营业时间。如果没有营业时间（即merchant_business_hours表不存在该商户关联的数据），则不允许更新为营业中
        if (bean.getStatus() == 1
                && merchantBusinessHoursMapper.selectCount(
                        Wrappers.<MerchantBusinessHours>lambdaQuery()
                                .eq(MerchantBusinessHours::getMerchantId, bean.getId())) == 0) {
            throw new BusinessException("请先设置营业时间");
        }
        //如果要更新为暂停营业，则设置closeMethod=1。
        if (bean.getStatus() == 0) {
            merchant.setCloseMethod(1); //商户手动关闭
        }else {
            merchant.setCloseMethod(0);
        }
        merchant.setStatus(bean.getStatus());
        merchantMapper.updateById(merchant);
    }
}
